/**
 * 模型设置抽屉 - 类似Cursor的模型选择界面
 */
import React, { useState, useEffect } from 'react';
import {
  Drawer,
  Card,
  Space,
  Input,
  Button,
  Tag,
  Avatar,
  Badge,
  Tooltip,
  Empty,
  Spin,
  Modal,
  Descriptions,
  Switch,
  Select
} from 'antd';
import {
  SearchOutlined,
  SettingOutlined,
  ThunderboltOutlined,
  StarOutlined,
  StarFilled,
  InfoCircleOutlined,
  FilterOutlined
} from '@ant-design/icons';
import { useModelDiscoveryStore } from '@/stores/model-discovery.store';
import { AvailableModel } from '@/services/model-discovery.service';
import ModelStatusIndicator from '../ModelStatusIndicator';
import './style.css';

interface ModelSettingsDrawerProps {
  open: boolean;
  onClose: () => void;
  selectedModelId?: string;
  onModelSelect?: (modelId: string) => void;
}

const ModelSettingsDrawer: React.FC<ModelSettingsDrawerProps> = ({
  open,
  onClose,
  selectedModelId,
  onModelSelect
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedProvider, setSelectedProvider] = useState<string>('all');
  const [showOnlyAvailable, setShowOnlyAvailable] = useState(false);
  const [detailModalOpen, setDetailModalOpen] = useState(false);
  const [detailModel, setDetailModel] = useState<AvailableModel | null>(null);
  
  const {
    availableModels,
    loading,
    searchModels,
    getModelsByProvider,
    getOnlineModels,
    getRecommendedModels,
    statistics
  } = useModelDiscoveryStore();
  
  // 获取提供商列表
  const providers = React.useMemo(() => {
    const providerSet = new Set(availableModels.map(m => m.provider));
    return Array.from(providerSet).sort();
  }, [availableModels]);
  
  // 过滤模型
  const filteredModels = React.useMemo(() => {
    let models = availableModels;
    
    // 搜索过滤
    if (searchQuery.trim()) {
      models = searchModels(searchQuery);
    }
    
    // 提供商过滤
    if (selectedProvider !== 'all') {
      models = models.filter(m => m.provider === selectedProvider);
    }
    
    // 可用性过滤
    if (showOnlyAvailable) {
      models = models.filter(m => m.status === 'available');
    }
    
    // 按推荐和状态排序
    return models.sort((a, b) => {
      // 推荐的排在前面
      if (a.recommended && !b.recommended) return -1;
      if (!a.recommended && b.recommended) return 1;
      
      // 可用的排在前面
      if (a.status === 'available' && b.status !== 'available') return -1;
      if (a.status !== 'available' && b.status === 'available') return 1;
      
      // 按响应时间排序
      if (a.responseTime && b.responseTime) {
        return a.responseTime - b.responseTime;
      }
      
      return a.displayName.localeCompare(b.displayName);
    });
  }, [availableModels, searchQuery, selectedProvider, showOnlyAvailable, searchModels]);
  
  // 处理模型选择
  const handleModelSelect = (model: AvailableModel) => {
    if (model.status !== 'available') return;
    
    if (onModelSelect) {
      onModelSelect(model.id);
    }
    onClose();
  };
  
  // 显示模型详情
  const showModelDetail = (model: AvailableModel) => {
    setDetailModel(model);
    setDetailModalOpen(true);
  };
  
  // 获取模型图标
  const getModelIcon = (provider: string) => {
    const icons: Record<string, string> = {
      openai: '🤖',
      anthropic: '🎭',
      claude: '🎭',
      deepseek: '🔍',
      google: '🔍',
      meta: '📘'
    };
    return icons[provider.toLowerCase()] || '🤖';
  };
  
  // 获取提供商颜色
  const getProviderColor = (provider: string) => {
    const colors: Record<string, string> = {
      openai: 'green',
      anthropic: 'purple',
      claude: 'purple',
      deepseek: 'blue',
      google: 'cyan',
      meta: 'orange'
    };
    return colors[provider.toLowerCase()] || 'default';
  };
  
  return (
    <>
      <Drawer
        title="选择模型"
        placement="right"
        width={480}
        open={open}
        onClose={onClose}
        className="model-settings-drawer"
      >
        {/* 搜索和过滤 */}
        <div className="drawer-header">
          <Input
            placeholder="搜索模型..."
            prefix={<SearchOutlined />}
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            style={{ marginBottom: 16 }}
          />
          
          <Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
            <Space>
              <Select
                value={selectedProvider}
                onChange={setSelectedProvider}
                style={{ width: 120 }}
                placeholder="提供商"
              >
                <Select.Option value="all">所有提供商</Select.Option>
                {providers.map(provider => (
                  <Select.Option key={provider} value={provider}>
                    {provider.charAt(0).toUpperCase() + provider.slice(1)}
                  </Select.Option>
                ))}
              </Select>
              
              <Switch
                checkedChildren="仅可用"
                unCheckedChildren="全部"
                checked={showOnlyAvailable}
                onChange={setShowOnlyAvailable}
              />
            </Space>
            
            {statistics && (
              <Space size={4}>
                <Badge status="success" text={`${statistics.available} 在线`} />
                <Badge status="error" text={`${statistics.unavailable} 离线`} />
              </Space>
            )}
          </Space>
        </div>
        
        {/* 推荐模型 */}
        {!searchQuery && selectedProvider === 'all' && (
          <div style={{ marginBottom: 24 }}>
            <h4 style={{ marginBottom: 12 }}>
              <StarFilled style={{ color: '#faad14', marginRight: 8 }} />
              推荐模型
            </h4>
            <div className="recommended-models">
              {getRecommendedModels().slice(0, 3).map(model => (
                <Card
                  key={model.id}
                  size="small"
                  hoverable
                  className={`model-card recommended ${selectedModelId === model.id ? 'selected' : ''}`}
                  onClick={() => handleModelSelect(model)}
                  actions={[
                    <InfoCircleOutlined onClick={(e) => {
                      e.stopPropagation();
                      showModelDetail(model);
                    }} />
                  ]}
                >
                  <Space>
                    <Avatar size="small">{getModelIcon(model.provider)}</Avatar>
                    <div>
                      <div className="model-name">{model.displayName}</div>
                      <ModelStatusIndicator modelId={model.id} size="small" />
                    </div>
                  </Space>
                </Card>
              ))}
            </div>
          </div>
        )}
        
        {/* 模型列表 */}
        <div className="models-list">
          {loading ? (
            <div style={{ textAlign: 'center', padding: 40 }}>
              <Spin size="large" />
              <div style={{ marginTop: 16 }}>加载模型中...</div>
            </div>
          ) : filteredModels.length === 0 ? (
            <Empty
              description="未找到匹配的模型"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          ) : (
            filteredModels.map(model => (
              <Card
                key={model.id}
                hoverable
                className={`model-card ${selectedModelId === model.id ? 'selected' : ''} ${
                  model.status !== 'available' ? 'disabled' : ''
                }`}
                onClick={() => handleModelSelect(model)}
                style={{ marginBottom: 12 }}
              >
                <div className="model-card-content">
                  <div className="model-header">
                    <Space>
                      <Avatar>{getModelIcon(model.provider)}</Avatar>
                      <div>
                        <div className="model-title">
                          <Space>
                            <span className="model-name">{model.displayName}</span>
                            {model.recommended && (
                              <StarFilled style={{ color: '#faad14', fontSize: 12 }} />
                            )}
                          </Space>
                        </div>
                        <div className="model-subtitle">
                          <Tag color={getProviderColor(model.provider)} size="small">
                            {model.providerName}
                          </Tag>
                          <ModelStatusIndicator modelId={model.id} size="small" />
                        </div>
                      </div>
                    </Space>
                    
                    <Button
                      type="text"
                      size="small"
                      icon={<InfoCircleOutlined />}
                      onClick={(e) => {
                        e.stopPropagation();
                        showModelDetail(model);
                      }}
                    />
                  </div>
                  
                  <div className="model-meta">
                    <Space split={<span>•</span>}>
                      <span>最大 {model.capabilities.maxTokens} tokens</span>
                      {model.responseTime && (
                        <span>
                          <ThunderboltOutlined /> {model.responseTime}ms
                        </span>
                      )}
                      {model.capabilities.supportsStreaming && (
                        <span>流式输出</span>
                      )}
                    </Space>
                  </div>
                </div>
              </Card>
            ))
          )}
        </div>
      </Drawer>
      
      {/* 模型详情弹窗 */}
      <Modal
        title={detailModel?.displayName}
        open={detailModalOpen}
        onCancel={() => setDetailModalOpen(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalOpen(false)}>
            关闭
          </Button>,
          detailModel?.status === 'available' && (
            <Button
              key="select"
              type="primary"
              onClick={() => {
                if (detailModel) {
                  handleModelSelect(detailModel);
                  setDetailModalOpen(false);
                }
              }}
            >
              选择此模型
            </Button>
          )
        ]}
        width={600}
      >
        {detailModel && (
          <div>
            <ModelStatusIndicator 
              modelId={detailModel.id} 
              showDetails 
              style={{ marginBottom: 16 }}
            />
            
            <Descriptions column={2} size="small">
              <Descriptions.Item label="提供商">
                <Tag color={getProviderColor(detailModel.provider)}>
                  {detailModel.providerName}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="模型名称">
                {detailModel.name}
              </Descriptions.Item>
              <Descriptions.Item label="最大Token">
                {detailModel.capabilities.maxTokens.toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="上下文窗口">
                {detailModel.capabilities.contextWindow.toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="流式输出">
                {detailModel.capabilities.supportsStreaming ? '支持' : '不支持'}
              </Descriptions.Item>
              <Descriptions.Item label="函数调用">
                {detailModel.capabilities.supportsFunctionCalling ? '支持' : '不支持'}
              </Descriptions.Item>
              <Descriptions.Item label="视觉能力">
                {detailModel.capabilities.supportsVision ? '支持' : '不支持'}
              </Descriptions.Item>
              {detailModel.responseTime && (
                <Descriptions.Item label="响应时间">
                  {detailModel.responseTime}ms
                </Descriptions.Item>
              )}
            </Descriptions>
            
            {detailModel.errorMessage && (
              <div style={{ marginTop: 16 }}>
                <h5>错误信息:</h5>
                <div style={{ padding: 8, background: '#fff2f0', borderRadius: 4, color: '#a8071a' }}>
                  {detailModel.errorMessage}
                </div>
              </div>
            )}
          </div>
        )}
      </Modal>
    </>
  );
};

export default ModelSettingsDrawer;